/*
Source : https://leetcode.com/problems/maximum-subarray/
Author : nflush@outlook.com
Date   : 2016-07-11
*/
/*
53. Maximum Subarray

    Total Accepted: 120699
    Total Submissions: 324886
    Difficulty: Medium

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

click to show more practice.

Subscribe to see which companies asked this question
*/
/*
算法复杂度O(n)
*/
class Solution
{
public:
    int maxSubArray(vector<int> &nums)
    {
        if(nums.size() == 0) return 0;
        int sum = nums[0];
        int cur = 0, count = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] >= 0) {
                cur += nums[i];
                count++;
            } else {
                if(count && cur > sum) {
                    sum = cur;
                } else {
                    if(nums[i] > sum) {
                        sum = nums[i];
                    }
                }
                if(cur + nums[i] > 0) {
                    cur += nums[i];
                } else {
                    cur = 0;
                }
            }
        }
        return count && cur > sum ? cur : sum;
    }
};

/*
1:找到第一个正数或者最大的负数 //8ms
2:统计所有正数和
3:遇到负数时,判断当前和是否比保存值大
4:跳过所有负数
2~4循环
*/
class Solution
{
public:
    int maxSubArray(vector<int> &nums)
    {
        if(nums.size() == 0) return 0;
        int sum = nums[0];
        int cur = 0;
        int i = 0;
        int negative_sum = 0;
        for(; i < nums.size(); i++) {
            if(nums[i] >= 0) {
                cur = nums[i];
                sum = cur;
                i++;
                break;
            } else {
                sum = max(sum, nums[i]);
            }
        }
        while(i < nums.size()) {
            if(nums[i] >= 0) {
                cur += nums[i++];
            } else {
                sum = max(sum, cur);
                do {
                    cur += nums[i++];
                } while(i < nums.size() && nums[i] <= 0);
                if(cur < 0) {
                    cur = 0;
                }
            }
        }
        return sum >= 0 && cur > sum ? cur : sum;
    }
};
